<template>
  <div>
    <h2>取消网络请求</h2>
    <p>Data:{{ data }}</p>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import axios, { type CancelTokenSource } from 'axios'
const data = ref()
let cancelTokenScource: CancelTokenSource | null = null

onMounted(() => {
  // 创建 Axios 取消令牌
  cancelTokenScource = axios.CancelToken.source()

  axios
    .get('https://jsonplaceholder.typicode.com/posts/1', {
      cancelToken: cancelTokenScource.token
    })
    .then((response) => {
      data.value = response.data
    })
    .catch((error) => {
      if (axios.isCancel(error)) {
        console.log('取消请求：', error.message)
      }
    })
})

onUnmounted(() => {
  // 组件卸载时取消请求
  if (cancelTokenScource) {
    cancelTokenScource.cancel('请求已取消，因为组件已卸载！')
  }
})
</script>

<style></style>
